home *** CD-ROM | disk | FTP | other *** search
/ ftp.cs.arizona.edu / ftp.cs.arizona.edu.tar / ftp.cs.arizona.edu / icon / newsgrp / group93c.txt / 000005_icon-group-sender _Tue Jul 6 16:43:02 1993.msg < prev    next >
Internet Message Format  |  1994-02-02  |  2KB

  1. Received: from owl.CS.Arizona.EDU by cheltenham.CS.Arizona.EDU; Tue, 6 Jul 1993 15:47:57 MST
  2. Received: by owl.cs.arizona.edu; Tue, 6 Jul 1993 15:47:56 MST
  3. Date: Tue, 6 Jul 93 16:43:02 EDT
  4. From: Paul_Abrahams@MTS.cc.Wayne.edu
  5. To: icon-group@cs.arizona.edu
  6. Message-Id: <696063@MTS.cc.Wayne.edu>
  7. Subject: Transmitting values to co-expressions
  8. Status: R
  9. Errors-To: icon-group-errors@cs.arizona.edu
  10.  
  11. The section of the Icon book that discusses transmission of values to
  12. co-expressions (p. 117) contains a non-obvious example of how
  13. transmission works, and also comments that it's very hard and perhaps not
  14. possible to find simple and well-motivated examples.  Well, recently I
  15. came upon a case where transmission of values to co-expressions is both
  16. useful and (reasonably) transparent.
  17.  
  18. It's easy enough to program a recursive procedure for writing the
  19. representation of an expression.  Wherever there are some characters to
  20. be generated, you just do "write" of those characters.  But suppose,
  21. instead, that you want to produce the =string image= of that expression.
  22. You can, of course, pass values back up the recursive chain, but that is
  23. less satisfying aesthetically.  What you really want to do is to write
  24. those values to a string, rather like the sprintf function in C.
  25.  
  26. Co-expressions provide a rather neat way of doing this.  You create a
  27. co-expression for generating the characters and then call it repeatedly,
  28. each time concatenating its results onto a string.  Within the generator,
  29. each time characters are to be output, you pass them to @source.  The
  30. following program illustrates the method:
  31.  
  32.    procedure main()
  33.    gen := create numbers()
  34.    result := ""
  35.    while result ||:= @gen
  36.    write(result)
  37.    end
  38.  
  39.    procedure numbers()
  40.       every ((i := 1 to 10) || ",") @ &source
  41.    end
  42.  
  43. This program will set =result= to "1,2,3,4,5,6,7,8,9,10," and then write
  44. it out.  Although =numbers= is nonrecursive, it could just as well be
  45. recursive.  Note that this program does the same thing as the following
  46. one:
  47.  
  48.    procedure main()
  49.    numbers()
  50.    write()
  51.    end
  52.  
  53.    procedure numbers()
  54.       every writes((i := 1 to 10)  || ",")
  55.    end
  56.  
  57. Paul Abrahams
  58. Reply-To: abrahams@acm.org
  59.